package com.laoye.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laoye.Exception.exception.BaseException;
import com.laoye.annotation.Log;
import com.laoye.bean.User;
import com.laoye.dto.*;
import com.laoye.mapper.UserMapper;
import com.laoye.service.UserService;
import com.laoye.util.EmailUtil;
import com.laoye.util.Page;
import com.laoye.util.ThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @CacheEvict(value = {"userInfo","user"},allEntries = true)
    @Override
    @Log("修改用户信息")
    public void editUser(UserEditDTO userInfo) {
        if (userInfo == null || userInfo.getId() == null) {
            throw new BaseException(401, "用户id不能为空");
        }
        Integer currentId = ThreadLocal.getCurrentId();  //用户修改自己的信息
        userInfo.setId(currentId);
        userMapper.editUser(userInfo);
    }

    @Cacheable(value = "username", key = "'username'+T(com.laoye.util.ThreadLocal).getCurrentId()")
    @Override
    public String findUsername(Integer id) {
        if (id == null) {
            throw new BaseException(401, "用户id不能为空");
        }
        return userMapper.findUsername(id);
    }


    /**
     * 根据用户名查询用户是否已经有账号存在
     *
     * @param registerDTO 前端注册的数据
     */
    @Transactional
    @CacheEvict(value = "userInfo",allEntries = true)
    @Override
    @Log(value="用户注册",printParam = true)
    public void register(RegisterDTO registerDTO) {
        if (registerDTO == null || registerDTO.getUsername() == null || registerDTO.getPassword() == null) {
            throw new BaseException(401, "用户名或密码不能为空");
        }
        String code = stringRedisTemplate.opsForValue().get("emailCode");
        if (code != null && !code.equals(registerDTO.getEmailCode())) {
            throw new BaseException(401, "邮箱验证码错误");
        }
        String username = registerDTO.getUsername();
        User user = userMapper.login(new LoginDTO(username, null)); // 查询用户名是否存在
        if (user == null) {
            String security = passwordEncoder.encode(registerDTO.getPassword());
            registerDTO.setPassword(security);
            userMapper.register(registerDTO);
        } else {
            throw new BaseException(401, "用户已存在");
        }
    }
    @Override
    @Log("用户登录")
    public User login(LoginDTO loginDTO) {
        // 检查输入参数
        if (loginDTO == null || loginDTO.getUsername() == null || loginDTO.getPassword() == null) {
            throw new BaseException(401, "用户名或密码不能为空");
        }

        // 先根据用户名查找用户
        User user = userMapper.getUserByName(loginDTO.getUsername());

        // 检查用户是否存在
        if (user == null) {
            throw new BaseException(401, "用户不存在");
        }

        // 验证密码是否正确
        boolean matches = passwordEncoder.matches(loginDTO.getPassword(), user.getPassword());
        if (!matches) {
            throw new BaseException(401, "密码错误");
        }
        return user;
    }

    @Transactional
    @Override
    @Log("修改密码")
    public void updatePassword(PwdEditDTO pwdEditDTO) {
        if (pwdEditDTO == null || pwdEditDTO.getId() == null || pwdEditDTO.getOldPassword() == null || pwdEditDTO.getNewPassword() == null) {
            throw new BaseException(401, "用户ID、旧密码或新密码不能为空");
        }
        pwdEditDTO.setId(ThreadLocal.getCurrentId());
        String encode = passwordEncoder.encode(pwdEditDTO.getNewPassword());
        pwdEditDTO.setNewPassword(encode);
        userMapper.updatePassword(pwdEditDTO);
        EmailUtil.sendEmail(userMapper.getEmail(ThreadLocal.getCurrentId()),
                "密码修改成功,请确保是本人操作,新的密码为:"+pwdEditDTO.getNewPassword()+"请勿泄露");
    }

    @Override
    @Log("用户登出")
    public void logout() {
        ThreadLocal.removeCurrentId();
    }

    /**
     * 获取用户列表
     *
     * @param keyword  模糊查询传参
     * @param pageNum  页数
     * @param pageSize 每页数据量
     * @return 返回Page<UserPageDTO>的包装数据
     */
    @Cacheable(value = "users",key = "'usersPage'+T(com.laoye.util.ThreadLocal).getCurrentId()")
    @Override
    public Page<UserPageDTO> getUsersPage(String keyword, Integer pageNum, Integer pageSize) {
//        1.开启分页查询，页码默认从1开始
        PageHelper.startPage(pageNum, pageSize);
//        2.执行查询，PageHelper自动添加分页条件
        List<UserPageDTO> users = userMapper.getUsersPage(keyword);
//        3.封装分页结果（PageInfo自动计算总记录数和总页数）
        PageInfo<UserPageDTO> pageInfo = new PageInfo<>(users);
//        4.简化分页结果
        Page<UserPageDTO> userPages = Page.<UserPageDTO>builder()
                .list(users)
                .total(pageInfo.getTotal())
                .totalPages(pageInfo.getPages())
                .pageNum(pageInfo.getPageNum())
                .pageSize(pageInfo.getPageSize())
                .build();
        return userPages;
    }

@CacheEvict(value = "avatar",key = "'userAvatar'+T(com.laoye.util.ThreadLocal).getCurrentId()")
    @Override
@Log("修改用户头像")
    public void updateAvatar(String file, Integer id) {
        if (file == null || id == null){
            throw new BaseException(401, "头像上传参数错误");
        }
       userMapper.updateAvatar(file, id);
    }

    @Cacheable(value = "avatar",key = "'userAvatar'+T(com.laoye.util.ThreadLocal).getCurrentId()",unless = "#result == null || #result.isEmpty()")
    @Override
    @Log("获取用户头像")
    public String getAvatarUrl(Integer id) {
        if (id == null){
            throw new BaseException(400, "用户id不能为空");
        }
        return userMapper.getAvatarUrl(id);
    }

    @Cacheable(value = "user",key = "T(com.laoye.util.ThreadLocal).getCurrentId()",unless = "#result == null")
    @Override
    @Log("获取用户信息")
    public User getUserById() {
        if (ThreadLocal.getCurrentId() == null){
            throw new BaseException(400, "用户id不能为空");
        }
        return userMapper.getUserById(ThreadLocal.getCurrentId());
    }

    @Log(value="发送邮箱验证码",printParam = true)
    @Override
    public void sendEmailCode(String email) {
        if (email == null){
            throw new BaseException(401, "邮箱不能为空");
        }
        int emailCode = (int) ((Math.random() * 900000) + 100000); // 生成 100000 到 999999 之间的随机数
        EmailUtil.sendEmail(email, "验证码为:" + emailCode);
        String code = String.valueOf(emailCode);
        stringRedisTemplate.opsForValue().set("emailCode", code, 5, TimeUnit.MINUTES);
    }
}
